// 运行时配置
// 全局初始化数据配置，用于 Layout 用户信息和权限初始化
// 更多信息见文档：https://umijs.org/docs/api/runtime-config#getinitialstate
import SearchInput from '@/components/Input';
import { RunTimeLayoutConfig, history } from '@umijs/max';
import { Dropdown, message, ConfigProvider } from 'antd';
import { MenuProps } from 'antd/lib';
import { RuntimeAntdConfig } from '@umijs/max';
import { theme } from 'antd';

// 从 localStorage 获取主题状态
const getThemeFromStorage = () => {
  const savedTheme = localStorage.getItem('isDarkTheme');
  return savedTheme === 'true';
};

// 保存主题状态到 localStorage
const saveThemeToStorage = (isDark: boolean) => {
  localStorage.setItem('isDarkTheme', isDark.toString());
};

// 全局主题状态
let isDarkTheme = getThemeFromStorage();

export async function getInitialState(): Promise<{ name: string }> {
  return { name: '@umijs/max' };
}

// 静态主题配置
const staticThemeConfig = {
  appConfig: {
    message: {
      maxCount: 3,
    }
  }
};

// 动态主题配置
export const antd: RuntimeAntdConfig = (memo) => {
  memo.theme ??= {};
  memo.theme.algorithm = isDarkTheme ? theme.darkAlgorithm : theme.defaultAlgorithm;
  return { ...memo, ...staticThemeConfig };
};

// 布局配置
export const layout: RunTimeLayoutConfig = () => {
  const dropdownItems: MenuProps['items'] = [
    {
      key: 'logout',
      label: '退出登录',
    },
    {
      key: 'theme',
      label: isDarkTheme ? '切换为亮色主题' : '切换为暗色主题',
    },
  ];

  const handleDropdownClick: MenuProps['onClick'] = ({ key }) => {
    if (key === 'logout') {
      history.push('/login');
    } else if (key === 'theme') {
      isDarkTheme = !isDarkTheme;
      saveThemeToStorage(isDarkTheme);
      
      // 使用 ConfigProvider 更新主题
      ConfigProvider.config({
        theme: {
          algorithm: isDarkTheme ? theme.darkAlgorithm : theme.defaultAlgorithm,
        },
      });
      
      message.success(`已切换为${isDarkTheme ? '暗色' : '亮色'}主题`);
      window.location.reload(); // 仍然需要刷新以确保所有组件更新
    }
  };

  return {
    logo: require('@/assets/imgs/logo.png'),
    menu: {
      locale: false,
    },
    layout: 'mix',
    splitMenus: true,
    avatarProps: {
      src: 'https://gw.alipayobjects.com/zos/antfincdn/efFD%24IOql2/weixintupian_20170331104822.jpg',
      size: 'small',
      title: 'admin',
      render: (_, dom: any) => {
        return (
          <div>
            <SearchInput />
            <Dropdown
              menu={{
                items: dropdownItems,
                onClick: handleDropdownClick,
              }}
            >
              {dom}
            </Dropdown>
          </div>
        );
      },
    },
  };
};

